import axios from 'axios'
import store from '@/store'
import configData from './config.js'
import tip from '_c/utils/tip'
import qs from 'qs'
import axiosAdapterUniapp from 'axios-adapter-uniapp'
const instance = axios.create({
	baseURL: configData.baseUrl,
	adapter: axiosAdapterUniapp,
	timeout: 300000,
	withCredentials: true
})

console.log('configData.baseUrl', configData.baseUrl)
const whiteList = [] // 白名单
// request拦截器
instance.interceptors.request.use(config => {
    
	if (whiteList.indexOf(config.url) !== -1) {
		return config
	}
	const token = store.getters.token || ''
	
	if(config.url.indexOf("/app/api/scan") !== -1){
		const tokenMerch = store.getters.tokenMerch || ''
		if (tokenMerch) {
			config.headers['token'] = tokenMerch;
		}
		if (config.qs && config.method.toUpperCase() === 'POST') {
			config.data = qs.stringify(config.data)
		}
		return config
		
	}
	
	if (token && !config.noToken) {
		config.headers['Authorization'] = `Bearer ${token}`
	}
	if (config.qs && config.methozd.toUpperCase() === 'POST') {
		config.data = qs.stringify(config.data)
	}
	return config
}, error => {
	return Promise.reject(error)
})

// respone拦截器
instance.interceptors.response.use((response, rs) => {
	if (whiteList.indexOf(response.url) !== -1 || whiteList.indexOf(response.config.url) !== -1) {
		return response.data
	}
	/**
	 * code为非200是抛错 可结合自己业务进行修改
	 */
	const res = response.data
	if (res.code !== 200 && res.msg) {
		uni.hideLoading();

		// 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
		if (res.code === 401 || res.code === 403) {
			tip.modal({
				content: '登录失效!即将前往登录!',
				showCancel: false
			}).then(() => {
				store.dispatch('StoreByLogout').then(() => {
					uni.reLaunch({
						url: '/pages/login/index'
					})
				})
			});

		} else {
			console.log(response, res)
			if (!response.config.noShowMsg) {
				tip.toast(res.msg)
			}
		}

	}
	return response.data
}, error => {
	uni.hideLoading();
	const msg = error == 'Error: Network Error' ? '服务器正在维护中,请稍后尝试' : '系统错误'
	tip.toast(msg)
	return Promise.reject(error)
})

export default instance
